﻿using ImageMagick;
using Toolbelt.Drawing;

namespace ElectronIconGenerator
{
    internal class G
    {
        public static string electronpath = Environment.CurrentDirectory;
        public static string filepath = Path.Combine(electronpath, @"public\icon.png");
        public static string buildpath = Path.Combine(electronpath, "build");
        public static string exepath = Path.Combine(electronpath, "dist_electron");
        public static List<int> customSizeList = new();
        public static bool isflatdist = true;
        public static int progressBarWidth;

        /// <summary>
        /// 将图片转换为ico格式图片
        /// 参数是一个由三个元素组成的列表，分别为string filepath、string icopath和int size
        /// </summary>
        /// <param name="arglist">三个元素组成的列表</param>
        public static void FileToICO(object? arglist)
        {
            if (arglist is not null)
            {
                //https://github.com/dlemstra/Magick.NET/blob/main/docs/Readme.md
                //修改尺寸并转换为ICO格式
                //@"C:\Users\AAA\Pictures\Girls\翼舞.webp"
                //@"C:\Users\AAA\Pictures\Girls\翼舞.ico"

                List<object> arglist1 = (List<object>)arglist;
                if (arglist1.Count == 3)
                {
                    var filepath = (string)arglist1[0];
                    var icopath = (string)((List<object>)arglist)[1];
                    var size = (int)((List<object>)arglist)[2];
                    if (size <= 0)
                    {
                        size = 1;
                    }
                    else if (256 < size)
                    {
                        size = 256;
                    }
                    using MagickImage i = new(filepath);
                    SquareSizeResize(i, size);
                    i.Write(icopath);
                }
            }
        }
        /// <summary>
        /// 将图片转换为多个不同尺寸的png格式图片
        /// 参数是一个由三个元素组成的列表，分别为string filepath、string distpath和List<int> customList
        /// </summary>
        /// <param name="arglist"></param>
        public static void FileToAllSizePNG(object? arglist)
        {
            if (arglist is not null)
            {
                List<object> arglist1 = (List<object>)arglist;
                if (arglist1.Count == 3)
                {
                    var filepath = (string)arglist1[0];
                    var distpath = (string)((List<object>)arglist)[1];
                    var customList = (List<int>)((List<object>)arglist)[2];

                    var sizeList = new List<int> { 16, 24, 32, 48, 64, 128, 256, 512 };
                    if (customList.Count > 0)
                    {
                        sizeList = customList;
                    }
                    foreach (var size in sizeList)
                    {
                        FileToPNG(filepath, Path.Combine(distpath, size + "x" + size + ".png"), size);
                    }
                }
            }
        }
        public static void FileToPII(object? arglist){
            FileToAllSizePNGandICO(arglist);
            FileToAllSizePNGandICNS(arglist);
            if (isflatdist is false)
            {
                var threepath = new string[] { "win", "mac", "png" };
                foreach (var path in threepath)
                {
                    if (!Directory.Exists(Path.Combine(buildpath, path)))
                    {
                        Directory.CreateDirectory(Path.Combine(buildpath, path));
                    }
                }
                File.Move(Path.Combine(buildpath, "icon.ico"), Path.Combine(buildpath, "win", "icon.ico"), true);
                File.Move(Path.Combine(buildpath, "icon.icns"), Path.Combine(buildpath, "mac", "icon.icns"), true);
                var pngfiles = Directory.GetFiles(buildpath,"*.png",SearchOption.TopDirectoryOnly);
                foreach (var png in pngfiles)
                {
                    File.Move(png, Path.Combine(buildpath, "png", Path.GetFileName(png)));
                }
            }
        }
        /// <summary>
        /// 将图片转换为多个不同尺寸的png格式图片和组合ico格式图片
        /// 参数有三个，分别为string filepath、string distpath和List<int> customList
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="distpath"></param>
        /// <param name="customList"></param>
        public static void FileToAllSizePNGandICO(string filepath, string distpath, List<int> customList)
        {
            var sizeList = new List<int> { 16, 24, 32, 48, 64, 128, 256, 512 };
            if (customList.Count > 0)
            {
                sizeList = customList;
            }
            using var AllPNG = new MagickImageCollection();
            foreach (var size in sizeList)
            {
                using MagickImage i = new(filepath);
                SquareSizeResize(i, size);
                i.Write(Path.Combine(distpath, size + "x" + size + ".png"));
                AllPNG.Add(i);
            }
            using var finallyICO = AllPNG.Mosaic();
            finallyICO.Write(Path.Combine(distpath, "icon.ico"));
        }
        /// <summary>
        /// 将图片转换为多个不同尺寸的png格式图片和组合ico格式图片
        /// 参数是一个由三个元素组成的列表，分别为string filepath、string distpath和List<int> customList
        /// </summary>
        /// <param name="arglist"></param>
        public static void FileToAllSizePNGandICO(object? arglist)
        {
            if (arglist is not null)
            {
                List<object> arglist1 = (List<object>)arglist;
                if (arglist1.Count == 1)
                {
                    ProgressBar progressBar = (ProgressBar)arglist1[0];
                    SetProgressBar(progressBar, -1);

                    List<int> sizeList = new() { 16, 24, 32, 48, 64, 128, 256 };
                    if (customSizeList.Count > 0)
                    {
                        sizeList = customSizeList;
                    }
                    for (int i = sizeList.Count - 1; i >= 0; i--)
                    {
                        if (sizeList[i] <= 0 || 256 < sizeList[i])
                        {
                            sizeList.RemoveAt(i);
                        }
                    }

                    SetProgressBar(progressBar, 25);

                    using var AllPNG = new MagickImageCollection();
                    List<MagickImage> imgList = new() { };
                    foreach (var size in sizeList)
                    {
                        imgList.Add(new MagickImage(filepath));
                    }

                    SetProgressBar(progressBar, 30);

                    for (int i = 0; i < sizeList.Count; i++)
                    {
                        SquareSizeResize(imgList[i], sizeList[i]);
                        AllPNG.Add(imgList[i]);
                        imgList[i].Write(Path.Combine(buildpath, sizeList[i] + "x" + sizeList[i] + ".png"));
                    }
                    AllPNG.Write(Path.Combine(buildpath, "icon.ico"));
                    SetProgressBar(progressBar, 50);
                }
            }
        }
        public static void FileToAllSizePNGandICNS(object? arglist) {
            if (arglist is not null)
            {
                List<object> arglist1 = (List<object>)arglist;
                if (arglist1.Count == 1)
                {
                    ProgressBar progressBar = (ProgressBar)arglist1[0];
                    SetProgressBar(progressBar, 51);
                    //List<int> sizeList = new() { 1024, 512, 512, 256, 256, 128, 64, 32, 32, 16 };
                    List<int> sizeList = new() { 1024 };
                    using var AllPNG = new MagickImageCollection();
                    List<MagickImage> imgList = new() { };
                    foreach (var size in sizeList)
                    {
                        imgList.Add(new MagickImage(filepath));
                    }
                    SetProgressBar(progressBar, 75);
                    for (int i = 0; i < sizeList.Count; i++)
                    {
                        SquareSizeResize(imgList[i], sizeList[i]);
                        AllPNG.Add(imgList[i]);
                    }
                    SetProgressBar(progressBar, 90);
                    AllPNG.Write(Path.Combine(buildpath, "icon.icns"));
                    SetProgressBar(progressBar, 100);
                    SetProgressBar(progressBar, 101);
                }
            }
        }
        public static void FileToPNG(string filepath, string pngpath, int size)
        {
            using MagickImage i = new(filepath);
            SquareSizeResize(i, size);
            i.Write(pngpath);
        }
        public static void SquareSizeResize(MagickImage i, int size)
        {
            i.Resize(SquareSize(size));
        }
        private static MagickGeometry SquareSize(int size)
        {
            return new MagickGeometry(size)
            {
                IgnoreAspectRatio = true
            };
        }

        public static void SetPic(PictureBox pictureBox, string filepath)
        {
            if (File.Exists(filepath))
            {
                FileStream fileStream = new(filepath, FileMode.Open, FileAccess.Read);
                
                pictureBox.Image = Image.FromStream(fileStream);
                fileStream.Close();
                fileStream.Dispose();
            }
            else
            {
                pictureBox.Image = null;
            }
        }
        public static void SetPic(PictureBox pictureBox, MagickImage image)
        {
            pictureBox.Image = image.ToBitmap();
        }
        public static string Findexe()
        {
            var exefile = "";
            if (Directory.Exists(G.exepath))
            {
                var files = Directory.GetFiles(G.exepath, "*.exe", SearchOption.TopDirectoryOnly);
                if (files.Length > 0)
                {
                    exefile = files.OrderBy(s => !s.Contains("Setup", StringComparison.OrdinalIgnoreCase)).First();
                }
            }
            return exefile;
        }

        /// <summary>
        /// 只能得到分辨率32x32的图标
        /// </summary>
        /// <param name="exefile"></param>
        public static void GetEXEIcon32(string exefile)
        {
            //var icon = Icon.ExtractAssociatedIcon(exefile);
            //FileStream fileStream = new(@"C:\Users\AAA\Desktop\1.png", FileMode.Create);
            //icon?.Save(fileStream);
            //fileStream.Dispose();
        }
        public static MagickImage GetEXEIconBig()
        {
            string exefile = Findexe();
            if (File.Exists(exefile)) {
                using var ms = new MemoryStream();
                IconExtractor.Extract1stIconTo(exefile, ms);
                ms.Seek(0, SeekOrigin.Begin);
                using var collection = new MagickImageCollection();
                collection.Read(ms, MagickFormat.Ico);
                var collection1 = collection.OrderByDescending(s => s.Height);
                var image = new MagickImage(collection1.First());
                return image;
            }
            else {
                return new MagickImage(new MagickColor("#6cf"),1,1);
            }
            
        }
        public static void SetProgressBar(ProgressBar progressBar, int pos)
        {
            if (progressBar is not null) {
                if (pos < 0)
                {
                    progressBar.Width = G.progressBarWidth;
                }
                else if (100 < pos) {
                    progressBar.Width = 0;
                }
                else
                {
                    progressBar.Value = pos;
                }
            }
        }
    }
}
